<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="700px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-form-item label="试卷标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入试卷标题" clearable/>
      </el-form-item>
      <el-form-item label="试卷类型" prop="type">
        <el-radio-group v-model="formData.type">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.EXAM_PAPER_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="题型设置" prop="franction" v-if="formData.franction">
        <div v-for="(item,index) in getStrDictOptions(DICT_TYPE.EXAM_TEST_TYPE)" :key="index" class="flex mb-10px w-1/1">
        <div>{{item.label}} 包含:</div>
        <el-input class="flex-1" v-model="formData.franction[item.value]['num']" placeholder="请输入数量" clearable/> <div>道&nbsp;&nbsp;</div>
        <div>每题:</div>
        <el-input  class="flex-1"  v-model="formData.franction[item.value]['score']" placeholder="请输入分数" clearable/><div>分&nbsp;&nbsp;</div>
        <div>题库{{item.label}}共1道</div>
   </div>
      </el-form-item>
      <el-form-item label="试卷总分值" prop="totalFranction">
        <el-input v-model="formData.totalFranction" placeholder="请输入试卷总分值" readonly clearable/>
      </el-form-item>
      <el-form-item label="试卷状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio
            v-for="dict in getIntDictOptions(DICT_TYPE.COMMON_STATUS)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="做题人数" prop="dnum">
        <el-input v-model="formData.dnum" placeholder="请输入做题人数" clearable/>
      </el-form-item>
      <el-form-item label="显示顺序" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入显示顺序" clearable/>
      </el-form-item>
      <el-form-item label="试卷价格" prop="price">
        <el-input v-model="formData.price" placeholder="请输入试卷价格" default-value="0" clearable/>
      </el-form-item>
      <el-form-item label="试卷时间" prop="times">
        <el-time-select
          v-model="formData.times"
          type="time"
          :start="'00:00'"
          :step="'00:05'"
          :end="'23:59'"
          value-format="HH:mm"
          placeholder="选择试卷时间单位(分)" clearable
        />
      </el-form-item>
      <el-form-item label="可重复答题" prop="isRepeat">
        <el-radio-group v-model="formData.isRepeat">
          <el-radio
            v-for="dict in getBoolDictOptions(DICT_TYPE.INFRA_BOOLEAN_STRING)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, getBoolDictOptions, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { PaperApi, PaperVO } from '@/api/exam/paper'

/** 试卷 表单 */
defineOptions({ name: 'PaperForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  title: undefined,
  type: undefined,
  franction: undefined,
  totalFranction: undefined,
  status: 0,
  dnum: undefined,
  sort: undefined,
  price: 0,
  times: undefined,
  isRepeat: true
})
watch(() => formData.value.franction, (val) => {
  if(val){
    formData.value.totalFranction=Object.values(val).reduce((acc:number, item:any) => acc + item.num * item.score, 0) as unknown as number
  }else{
    formData.value.totalFranction=0
  }
}, { deep: true, immediate: true })
const formRules = reactive({
  title: [{ required: true, message: '试卷标题不能为空', trigger: 'blur' }],
  franction: [{ required: true, message: '每个题型有多少  每个题多少分不能为空', trigger: 'blur' }],
  price: [{ required: true, message: '试卷价格默认0不能为空', trigger: 'blur' }],
  times: [{ required: true, message: '试卷时间单位分不能为空', trigger: 'blur' }],
  isRepeat: [{ required: true, message: '重复答题 1可以 2否不能为空', trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await PaperApi.getPaper(id)
    } finally {
      formLoading.value = false
    }
  }
  if(formData.value.franction){
    formData.value.franction=JSON.parse(formData.value.franction)
  }else{
    formData.value.franction={}
    getStrDictOptions(DICT_TYPE.EXAM_TEST_TYPE).forEach((item)=>{
      formData.value.franction[item.value]={
            num: 0,
            score: 0
          }
        })
  } 
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as PaperVO
    data.franction=JSON.stringify(data.franction)
    data.times=data.times.split(':')[0]*60*60+data.times.split(':')[1]*60
    if (formType.value === 'create') {
      await PaperApi.createPaper(data)
      message.success(t('common.createSuccess'))
    } else {
      await PaperApi.updatePaper(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    type: undefined,
    franction: undefined,
    totalFranction: undefined,
    status: 0,
    dnum: undefined,
    sort: undefined,
    price: 0,
    times: undefined,
    isRepeat: true
  }
  formRef.value?.resetFields()
}
</script>